package com.team.ai.tool.Juhe.Current;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Map;

public class RequestTool {
    public String doGet(String httpUrl,String queryParams){
        HttpURLConnection connection = null;
        InputStream inputStream=null;
        BufferedReader bufferedReader=null;
        String result=null;
        try {
            //创建远程url链接对象
            URL url=new URL(new StringBuffer(httpUrl).append("?").append(queryParams).toString());
            //通过远程url连接对象打开一个链接强转成httpurlconnection类
            connection =(HttpURLConnection) url.openConnection();
            //设置链接方式get
            connection.setRequestMethod("GET");
            //发送请求
            connection.connect();
            //通过connection链接 获取输入流
            if (connection.getResponseCode() ==200){
                inputStream=connection.getInputStream();
                //封装输入流，并制定字符集
                bufferedReader =new BufferedReader(new InputStreamReader(inputStream,StandardCharsets.UTF_8));
                //存放数据
                StringBuffer sbf=new StringBuffer();
                String temp;
                while ((temp= bufferedReader.readLine())!=null){
                    sbf.append(temp);
                    sbf.append(System.getProperty("line.separator"));
                }
                result =sbf.toString();
            }
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            //关闭资源
            if (null != bufferedReader){
                try{
                    bufferedReader.close();
                }catch (IOException e){
                    e.printStackTrace();
                }
            }
            if (null != inputStream){
                try{
                    inputStream.close();
                }catch (IOException e){
                    e.printStackTrace();
                }
            }
            if (connection != null){
                connection.disconnect();//关闭远程链接
            }

        }
        return result;
    }

    /**
     * 将map类型转换为请求参数
     * @param data 参数
     * @return String
     */
    public String urlencode(Map<String,?> data){
        StringBuilder sb=new StringBuilder();
        for (Map.Entry<String,?>i:data.entrySet()){
            try{
                sb.append(i.getKey()).append("=").append(URLEncoder.encode(i.getValue()+"","UTF-8")).append("&");
            }catch (UnsupportedEncodingException e){
                e.printStackTrace();
            }
        }
        String result=sb.toString();
        result =result.substring(0,result.lastIndexOf("&"));
        return result;
    }
}
